import { defineComponent } from "vue";
import type { PropType } from "vue";
import { queryRender } from "@/views/table/fragment/query-render/index";
import { tableRender } from "@/views/table/fragment/table-render";
import { dialogRender } from "@/views/table/fragment/dialog-render";
import type { Templates } from "@/views/table/types";
import { Button, Popconfirm } from "@arco-design/web-vue";
import { useTable } from "@/views/table/hooks/table";
import { PaginationRender } from "@/views/table/fragment/pagination-render";
export default defineComponent({
  name: "table-view",
  props: {
    templates: {
      type: Object as PropType<Templates>,
      required: true,
    },
  },
  setup(prop, { emit, expose }) {
    const {
      st,
      visible,
      resetSearch,
      tableData,
      getTableData,
      deleteTableData,
      getTableDataDetail,
      updateTableData,
      formRef,
      modeObj,
      createTableData,
    } = useTable();
    const search = () => {
      // console.log(st.query);
      getTable();
    };
    const getQuery = () => ({ ...st.page, ...st.query });
    const getTable = () => {
      const callback = (res: any) => {
        if (prop.templates.tableDataProcess) {
          /*
          手动处理表格数据和后端接口数据
           */
          prop.templates.tableDataProcess(res, tableData, st.page);
          return;
        }
        if (res?.data instanceof Array) {
          tableData.value = res.data;
        } else {
          tableData.value = [];
          console.warn("数据格式不符,请手动调用tableDataProcess函数处理");
        }
        console.log(tableData.value);
      };
      getTableData({
        baseUrl: prop.templates.baseUrl,
        url: prop.templates.api,
        query: st.query,
        callback,
      });
    };
    const submitMap = {
      detail: () => {},
      create: prop.templates.onCreate
        ? prop.templates.onCreate
        : createTableData,
      update: prop.templates.onUpdate
        ? prop.templates.onUpdate
        : updateTableData,
    };
    const beforeSubmitMap = {
      detail: () => {},
      create: prop.templates.onBeforeCreate
        ? prop.templates.onBeforeCreate
        : undefined,
      update: prop.templates.onBeforeUpdate
        ? prop.templates.onBeforeUpdate
        : undefined,
    };
    const doDetail = (row: any) => {
      st.currMode = "detail";
      const { api, baseUrl, models } = prop.templates;
      getTableDataDetail(row, {
        api,
        baseUrl,
        emit,
        models,
        visible,
        currMode: st.currMode,
        callback: () => {
          visible.value = true;
        },
      });
    };
    const doUpdate = (row: any) => {
      const { api, baseUrl, models } = prop.templates;
      st.currMode = "update";
      getTableDataDetail(row, {
        api,
        baseUrl,
        emit,
        models,
        visible,
        currMode: st.currMode,
        callback: () => {
          visible.value = true;
        },
      });
    };
    const doDelete = (row: any) => {
      const { api, baseUrl, models } = prop.templates;
      deleteTableData(row, {
        api,
        baseUrl,
        emit,
        models,
        visible,
        currMode: st.currMode,
        callback: () => {
          initTable();
          // visible.value = true;
        },
      });
    };
    const doCreate = () => {
      st.currMode = "create";
      visible.value = true;
    };
    const initTable = () => {
      const temp: any = {};
      const tableConfigs = prop.templates.models.filter(
        (it) => it.visible?.filter || true
      );
      /*
      将自定义内容处理成插槽对象
       */
      // @ts-ignore
      st.columns = tableConfigs
        .filter((it) => {
          if (it.visible?.filter === undefined) {
            return true;
          }
          return it.visible?.filter;
        })
        .map((it) => {
          return it.renderItem?.filter
            ? {
                dataIndex: it.field,
                slotName: it.field, // 添加插槽方便自定义
                ...it,
              }
            : { dataIndex: it.field, ...it };
        });
      tableConfigs
        .filter((it) => it.renderItem?.filter)
        .forEach((it) => {
          temp[it.field] = it.renderItem?.filter;
        });
      /**
       * 模板未设置action选项且之前没有action插槽
       */
      if (!prop.templates.actions) {
        temp.actions = (row: any) => (
          <div>
            <Button
              class="mr-2"
              type="outline"
              size="mini"
              style="color: gray;border-color: gray;"
              onClick={() => {
                doDetail(row);
              }}
            >
              详情
            </Button>
            <Button
              class="mr-2"
              type="outline"
              size="mini"
              onClick={() => {
                doUpdate(row);
              }}
            >
              编辑
            </Button>
            <Popconfirm
              content="确认删除吗?"
              type="warning"
              onOk={() => {
                doDelete(row);
              }}
            >
              <Button class="" type="outline" status="danger" size="mini">
                删除
              </Button>
            </Popconfirm>
          </div>
        );
      } else {
        /*
        自定义操作列
         */

        temp.actions = (row: any) => (
          <div>
            {/*@ts-ignore*/}
            {Object.keys(prop.templates.actions)
              .filter((it) => it !== "create")
              .map((it) =>
                prop.templates.actions[it](row, {
                  doDelete,
                  doDetail,
                  doUpdate,
                })
              )}
          </div>
        );
      }
      st.slots = temp;
      console.log(st.slots);
      prop.templates.actions !== null &&
        st.columns.push({
          title: "操作",
          slotName: "actions",
          align: "center",
        });
      // console.log(st.columns);
      getTable();
    };
    initTable();
    expose({
      getQuery,
    });
    return () => (
      <div>
        <div>
          {queryRender({
            models:
              prop.templates?.models.filter(
                (it) => it.visible?.query || false
              ) || [],
            onSearch: search,
            query: st.query,
            emit,
          })}
          {prop.templates.actions?.create ? (
            prop.templates.actions.create(doCreate)
          ) : (
            <div class="flex justify-end mt-2 mx-4">
              <Button
                type="outline"
                status="success"
                onClick={() => {
                  doCreate();
                }}
              >
                新增
              </Button>
            </div>
          )}

          {tableRender({
            tableData: tableData,
            columns: st.columns,
            slots: st.slots,
          })}
          {PaginationRender({
            size: st.page.size,
            current: st.page.current,
            total: st.page.total,
            align: prop.templates.pagination?.align || "center",
            currentChange: (val) => {
              st.page.current = val;
              getTable();
            },
          })}
          {dialogRender({
            title: prop.templates[st.currMode]?.title
              ? prop.templates[st.currMode]?.title || ""
              : "",
            layout: prop.templates[st.currMode]?.layout
              ? prop.templates[st.currMode]?.layout || "vertical"
              : "vertical",
            visible: visible,
            formRef: formRef,
            formModel: modeObj[st.currMode],
            currMode: st.currMode,
            models: prop.templates.models.filter((it) =>
              it.visible ? it.visible[st.currMode] || true : true
            ),
            baseUrl: prop.templates.baseUrl,
            api: prop.templates.api,
            emit,
            submit: submitMap[st.currMode],
            beforeSubmit: beforeSubmitMap[st.currMode],
            callback: initTable,
          })}
        </div>
      </div>
    );
  },
});
